package com.firefightingiot_data.data.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.firefightingiot_data.data.common.base.BaseService;
import com.firefightingiot_data.data.common.utils.appkit.FirefightingiotKit;
import com.firefightingiot_data.data.support.model.RespEntity;
import com.firefightingiot_data.data.support.mybatisplus.QueryWrapper;
import com.firefightingiot_data.data.support.utils.MyLogger;
import com.firefightingiot_data.data.web.mapper.*;
import com.firefightingiot_data.data.web.model.DeviceAlarmEvent;
import com.firefightingiot_data.data.web.model.DeviceAlarmLog;
import com.firefightingiot_data.data.web.model.DeviceAlarmLogImg;
import com.firefightingiot_data.data.web.model.DeviceBusiness;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: YangYu
 * @ClassName: AlarmService
 * @Date: Created in 11:04 2022/4/21
 * @Description:
 */
@Service
@Slf4j
public class AlarmService extends BaseService {


    @Resource
    public MyLogger logger;
    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    @Resource
    private DeviceAlarmLogMapper deviceAlarmLogMapper;
    @Resource
    private DeviceAlarmLogAllTodayMapper deviceAlarmLogAllTodayMapper;
    @Resource
    private DeviceAlarmLogImgMapper deviceAlarmLogImgMapper;
    @Resource
    private FireAddAlarmService alarmAddFireService;
    @Resource
    private DeviceNormalLogMapper deviceNormalLogMapper;
    @Resource
    private DeviceAlarmEventMapper deviceAlarmEventMapper;

    /**
     * 报警日志添加
     *
     * @param
     * @return
     */
    public RespEntity add(JSONObject jsonParam) throws ParseException, InterruptedException {
        //处理支持form-data和json两种方式
        //jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        logger.info("----------iotalramadd" + jsonParam.toString() + "--------------------");
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusiness.isEmpty()) return RespEntity.fail("设备编号错误");
        //更新最新时间的和设备的状态为报警
        DeviceBusiness deviceBusinessN = new DeviceBusiness();
        deviceBusinessN.setId(deviceBusiness.getId());
        deviceBusinessN.setNormalUpdateTime(DateUtil.now());
        deviceBusinessN.setCurrentstate("2");
        //deviceBusinessMapper.updateById(deviceBusinessN);
        //rest请求单位详情接口，获取单位信息
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("homeId", deviceBusiness.get("org_id"));
        jsonParamN.put("id", deviceBusiness.get("business_id"));
        com.alibaba.fastjson.JSONObject businessDetail = makeData(jsonParamN, "businessJava", "config", "getBusinessDetailNoToken", "business");
        if (StrUtil.isNotBlank(businessDetail.getString("methodErrorFlag")))
            return RespEntity.fail(businessDetail.getString("msg"));
        //赋值数据和保存数据:DeviceAlarmLog
        DeviceAlarmLog deviceAlarmLog = new DeviceAlarmLog();
        String id = "";
        if (deviceBusiness.get("device_classify").equals("6")) {
            id = jsonParam.getStr("uuid");
        } else {
            id = UUID.randomUUID().toString();
        }
        if (deviceBusiness.get("device_classify").equals("5")) {
            String[] content = jsonParam.getStr("content").split(",");
            if (content.length > 1 && content[2].equals("未定义")) {
                if (StrUtil.isNotBlank(deviceBusiness.getStr("part_type_id"))) {
                    Map<String, String> map = deviceBusinessMapper.getPartType(deviceBusiness.getStr("part_type_id"));
                    jsonParam.put("content", content[0] + "," + content[1] + "," + map.get("name"));
                }
            }
        }
        deviceAlarmLog.setId(id);
        deviceAlarmLog.setAllId(deviceBusiness.get("all_id").toString());
        jsonParam.put("orgIds", deviceBusiness.get("all_id").toString());
        deviceAlarmLog.setDeviceId(deviceBusiness.get("id").toString());
        deviceAlarmLog.setNumber(deviceBusiness.get("number").toString());
        deviceAlarmLog.setDeviceClassify(deviceBusiness.get("device_classify").toString());
        deviceAlarmLog.setDeviceType(deviceBusiness.get("device_type").toString());
        deviceAlarmLog.setAlarmType(jsonParam.getStr("alarmType"));
        deviceAlarmLog.setAlarmTypeName(jsonParam.getStr("alarmTypeName"));
        deviceAlarmLog.setContent(jsonParam.getStr("content"));
        deviceAlarmLog.setAlarmtime(jsonParam.getDate("alarmtime"));
        deviceAlarmLog.setPosition(deviceBusiness.get("position").toString());
        deviceAlarmLog.setOrgId(deviceBusiness.get("org_id").toString());
        deviceAlarmLog.setBusinessId(deviceBusiness.get("business_id").toString());
        deviceAlarmLog.setBusinessName(deviceBusiness.get("business_name").toString());
        deviceAlarmLog.setFireRating(businessDetail.getString("fireRating"));
        deviceAlarmLog.setDeviceName(deviceBusiness.getName());
        deviceAlarmLog.setHandle(false);
        if (StrUtil.isNotBlank(deviceBusiness.getStr("alarm_phone"))) {
            deviceAlarmLog.setAlarmPhone(deviceBusiness.get("alarm_phone").toString());
        }
        deviceAlarmLog.setSupervise("督办");
        deviceAlarmLog.setHandletime(null);
        deviceAlarmLog.setHandlePerson(null);
        deviceAlarmLog.setInfoconfirm(null);
        deviceAlarmLog.setHandleRemark(null);
        deviceAlarmLog.setUnreadstate(false);
        deviceAlarmLog.setArea(businessDetail.getString("area"));
        deviceAlarmLog.setAreaName(businessDetail.getString("areaName"));
        String areaName[] = businessDetail.getString("areaName").split(",");
        if (areaName.length >= 3) {
            deviceAlarmLog.setCity(areaName[1]);
            deviceAlarmLog.setRegion(areaName[2]);
        } else if (areaName.length >= 4) {
            deviceAlarmLog.setCity(areaName[1]);
            deviceAlarmLog.setRegion(areaName[2]);
            deviceAlarmLog.setStreet(areaName[3]);
        }
        deviceAlarmLog.setIsws(jsonParam.getInt("isws"));
        deviceAlarmLog.setFireId(UUID.randomUUID().toString().replace("-", ""));
        deviceAlarmLogMapper.insert(deviceAlarmLog);
        if (deviceBusiness.get("device_classify").equals("1")) {
            deviceAlarmLog.put("table", "device_alarm_log_electric_fire_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.get("device_classify").equals("2")) {
            deviceAlarmLog.put("table", "device_alarm_log_fire_water_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.get("device_classify").equals("3")) {
            deviceAlarmLog.put("table", "device_alarm_log_smoke_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.get("device_classify").equals("4")) {
            deviceAlarmLog.put("table", "device_alarm_log_gas_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.get("device_classify").equals("5")) {
            deviceAlarmLog.put("table", "device_alarm_log_auto_network_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.get("device_classify").equals("6")) {
            deviceAlarmLog.put("table", "device_alarm_log_visualization_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.get("device_classify").equals("7")) {
            deviceAlarmLog.put("table", "device_alarm_log_fire_extinguisher_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.get("device_classify").equals("10")) {
            deviceAlarmLog.put("table", "device_alarm_log_water_pump_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.get("device_classify").equals("20")) {
            deviceAlarmLog.put("table", "device_alarm_log_water_immersion_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.get("device_classify").equals("22")) {
            deviceAlarmLog.put("table", "device_alarm_log_charging_station_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        }
        deviceAlarmLog.put("table", "device_alarm_log_all_today");
        deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        if (StrUtil.isNotBlank(jsonParam.getStr("path"))) {
            String[] imgs = jsonParam.getStr("path").split(";;");
            int ii = 0;
            for (String img : imgs) {
                ii = ii + 1;
                DeviceAlarmLogImg deviceAlarmLogImg = new DeviceAlarmLogImg();
                deviceAlarmLogImg.setId(UUID.randomUUID().toString());
                deviceAlarmLogImg.setDeviceAlarmLogId(id);
                deviceAlarmLogImg.setAlarmOrResolve(1);
                deviceAlarmLogImg.setPath(img);
                if (ii == 1) {
                    deviceAlarmLogImg.setName("报警图片地址");
                    deviceAlarmLogImg.setType(1);
                } else {
                    deviceAlarmLogImg.setName("报警视频地址");
                    deviceAlarmLogImg.setType(2);
                }
                deviceAlarmLogImgMapper.insert(deviceAlarmLogImg);
            }
        }
        jsonParam.put("businessId", deviceAlarmLog.getBusinessId());
        jsonParam.put("position", deviceAlarmLog.getPosition());
        jsonParam.put("deviceClassify", deviceAlarmLog.getDeviceClassify());
        //app个推
        //msgPushService.msgPush(jsonParam);
        jsonParam.put("businessName", businessDetail.getString("name"));
        jsonParam.put("deviceName", deviceBusiness.getStr("name"));
        jsonParam.put("oneResponPersonName", businessDetail.getString("oneResponPersonName"));
        jsonParam.put("oneResponPersonPhone", businessDetail.getString("oneResponPersonPhone"));
        logger.info("++++++++++weChatMsgPush++++++++" + jsonParam);
        //TODO微信报警信息推送
        //数据订阅
        jsonParam.put("type", "alarm");
        jsonParam.put("deviceId", deviceBusiness.get("id").toString());
        jsonParam.put("addr", businessDetail.getString("addr"));
        jsonParam.put("area", businessDetail.getString("areaName"));
        jsonParam.put("safeManagePersonName", businessDetail.getString("safeManagePersonName"));
        jsonParam.put("safeManagePersonPhone", businessDetail.getString("safeManagePersonPhone"));
        jsonParam.put("safeResponPersonName", businessDetail.getString("safeResponPersonName"));
        jsonParam.put("safeResponPersonPhone", businessDetail.getString("safeResponPersonPhone"));
        jsonParam.put("lon", businessDetail.getString("lon"));
        jsonParam.put("lat", businessDetail.getString("lat"));
        //msgPushService.alarmDataPush(jsonParam);
        // 报警事件新增
        setEvent(id, jsonParam.getStr("alarmtime"));
        //报警内容
        String str = jsonParam.getStr("alarmStr");
        if (str == null || str.isEmpty() || !jsonParam.containsKey("alarmStr")) {
            return RespEntity.success(id);
        }
        return RespEntity.success(id);
    }

    /**
     * @Author YangYu
     * @Description 报警事件新增
     * @Date Created in 15:34 2024/4/15
     * @Param [id]
     */

    private void setEvent(String id, String time) {
        DeviceAlarmEvent deviceAlarmEvent = new DeviceAlarmEvent();
        deviceAlarmEvent.setDeviceAlarmLogId(id);
        deviceAlarmEvent.setTime(time);
        deviceAlarmEvent.setEventName("事件报警");
        deviceAlarmEventMapper.insert(deviceAlarmEvent);
    }

    /**
     * @Author YangYu
     * @Description 批量消防支队处置
     * @Date Created in 15:28 2022/10/8
     * @Param [jsonObject]
     */

    public void batchFileHandle(JSONObject jsonObject) throws InterruptedException {
        //批量传参{"deviceClassify":"2","alarmtime":"2022-10-05"}
//        List<DeviceAlarmLog> logList = deviceAlarmLogMapper.deviceAlarmLogList(jsonObject);
//        for (DeviceAlarmLog alarmLog : logList){
//            String businessflag = deviceNormalLogMapper.getExpirationTime(alarmLog.getString("business_id"));
//            if (!businessflag.equals("已过期")){
//                jsonObject = new JSONObject();
//                jsonObject.put("number",alarmLog.getNumber());
//                jsonObject.put("fireId",alarmLog.getString("fire_id"));
//                jsonObject.put("alarmtime",alarmLog.getAlarmtime());
//                alarmAddFireService.restRecoverFile(jsonObject);
//                alarmAddFireService.restFileHandle(jsonObject);
//            }
//        }
        //单个传参{"number":"863716041028314","fireId":"2c8846f985024e9f9cabf4da31877e2f","alarmtime":"2022-10-08 12:41:32"}
        alarmAddFireService.restRecoverFile(jsonObject);
        alarmAddFireService.restFileHandle(jsonObject);
    }


    /**
     * @Author YangYu
     * @Description cmd命令执行
     * @Date Created in 17:23 2023/5/31
     * @Param [cmds]
     */

    public static String execCurl(String[] cmds) {

        ProcessBuilder process = new ProcessBuilder(cmds);

        Process p;

        try {

            p = process.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            StringBuilder builder = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {

                builder.append(line);

                builder.append(System.getProperty("line.separator"));

            }

            return builder.toString();

        } catch (IOException e) {

            System.out.print("error");

            e.printStackTrace();

        }

        return null;

    }
}
